﻿using System;
using System.IO;
using System.Configuration;
using System.Windows.Forms;

using DreamCube.Foundation.Basic.Utility;

namespace WebServer.WebHostDll40.UI
{
    public partial class MainForm : Form
    {
        private Boolean isRunning = false;
        private Server webServer = null;

        public MainForm()
        {
            InitializeComponent();
            InitialData();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitialData()
        {
            try
            {
                txt_port.Text = ConfigurationManager.AppSettings["WebPort"];
                txt_PhysicalPath.Text = ConfigurationManager.AppSettings["WebPath"];
                txt_DefaultDoc.Text = ConfigurationManager.AppSettings["DefaultDocs"];
                lb_serverState.Text = "停止";
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 启动服务器按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (isRunning)
            {
                StopServer();
            }
            else
            {
                try
                {
                    Int32 port = 80;
                    if (!(Int32.TryParse(txt_port.Text, out port) && port >= 1 && port <= 6000))
                    {
                        MessageBox.Show("端口号必须为1-6000");
                        return;
                    }
                    if (String.IsNullOrEmpty(txt_PhysicalPath.Text) || !Directory.Exists(txt_PhysicalPath.Text))
                    {
                        MessageBox.Show("指定的目录不存在");
                        return;
                    }
                    //默认文档
                    String defaultDoc = ConfigurationManager.AppSettings["DefaultDocs"];
                    if (!String.IsNullOrEmpty(txt_DefaultDoc.Text))
                    {
                        defaultDoc = txt_DefaultDoc.Text;
                    }

                    CopyDll(); //先复制依赖的dll
                    webServer = new Server(port, "/", txt_PhysicalPath.Text, true, false);
                    webServer.Start();

                    isRunning = true;
                    lb_serverState.Text = "运行ing";
                    btn_StartServer.Text = "停止服务器";

                    txt_port.Enabled = false;
                    txt_PhysicalPath.Enabled = false;
                    txt_DefaultDoc.Enabled = false;
                }
                catch (Exception ex)
                {
                    MyLog.MakeLog(ex);
                    lb_serverState.Text = "启动服务器发生异常，请联系South！";
                    btn_StartServer.Text = "启动服务器";
                }
            }
        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        private void StopServer()
        {
            try
            {
                if (webServer != null) webServer.Stop();
                txt_port.Enabled = true;
                txt_PhysicalPath.Enabled = true;
                txt_DefaultDoc.Enabled = true;

                webServer = null;
                isRunning = false;
                lb_serverState.Text = "停止";
                btn_StartServer.Text = "启动服务器";
                DeleteDll();
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 确保删除了dll，否则影响IIS的部署
        /// </summary>
        private void DeleteDll()
        {
            String path = Path.Combine(txt_PhysicalPath.Text, "bin");
            String fileName = ConfigurationManager.AppSettings["HostDllFileName"];
            if (String.IsNullOrEmpty(fileName)) fileName = "WebServer.WebHostDll.dll";
            String dllFile = Path.Combine(path, fileName);
            String pdbFile = Path.Combine(path, MyString.LeftOfLast(fileName, ".", false, "") + ".pdb");
            MyIO.FileDelete(dllFile);
            MyIO.FileDelete(pdbFile);
        }

        /// <summary>
        /// 复制依赖的dll和调试的pdb
        /// </summary>
        private void CopyDll()
        {
            String path = AppDomain.CurrentDomain.BaseDirectory;
            String fileName = ConfigurationManager.AppSettings["HostDllFileName"];
            if (String.IsNullOrEmpty(fileName)) fileName = "WebDev.WebHost40.dll";
            String dllFile = Path.Combine(path, fileName);
            if (File.Exists(dllFile))
            {
                MyIO.FileCopy(dllFile, Path.Combine(txt_PhysicalPath.Text, "bin"), true, "");
            }
            else
            {
                throw new Exception("承载服务器的dll找不到，联系管理员");
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopServer();
        }
    }
}
